<template>
  <div v-loading="loading" class="action-app-form">
    <div class="action-app-form-item">
      <div class="title">{{ $t('trigger.text2') }}</div>
      <el-select
        v-model="currentExecuteWay"
        :placeholder="$t('common.connector.tips.tip4')"
        style="width:100%;"
      >
        <el-option
          v-for="trigger in executeWayList"
          :key="trigger.way"
          :value="trigger.way"
          :label="trigger.wayName"
        ></el-option>
      </el-select>
    </div>
    <div v-if="currentExecuteWay == 'event'" class="action-app-form-item">
      <div class="title">{{ $t('trigger.text3') }}</div>
      <el-cascader
        class="trigger-action-select" 
        ref="TriggleActionSelectComponent"
        v-model="action"
        :options="options"
        :props="props"
        @change="handleTreeSelect"
        :disabled="!canChoose">
      </el-cascader>
    </div>
    <div v-else-if="currentExecuteWay == 'webhook'" class="action-app-form-item">
      <div class="title">{{ $t('trigger.text4') }}</div>
      <p class="trigger-tip">{{ $t('trigger.text5') }}</p>
      <div class="url-input">
        <el-tooltip effect="dark" :content="webHookConfig.url">
          <el-input v-model="webHookConfig.url" disabled></el-input>
        </el-tooltip>
        <el-button type="primary" @click="copyLink(webHookConfig.url)">{{ $t('common.base.copy') }}</el-button>
      </div> 
      <div class="title">{{ $t('trigger.text6') }}</div>
      <div class="webhook-config-param-template">
        <el-input
          v-model="webHookConfig.paramTemplate"
          type="textarea"
          :autosize="{ minRows: 3, maxRows: 10 }"
          disabled />
        <el-button type="primary" @click="copyLink(webHookConfig.paramTemplate)">{{ $t('common.base.copy') }}</el-button>
      </div>
    </div>

    <div class="action-app-form-item" v-if="currentExecuteWay === 'timer'">
      <el-radio-group class="mar-t-16 mar-b-8 w-100-p" v-model="timeOptions.timerTab">
        <el-radio-button class="max-w-50-p" label="diy"><span class="overHideCon-1">{{ $t('connector.setting.label6') }}</span></el-radio-button>
        <el-radio-button class="max-w-50-p" label="corn"><span class="overHideCon-1">{{ $t('connector.setting.label7') }}</span></el-radio-button>
      </el-radio-group>
      <el-form  ref="actionByTimeFormDom" class="diy-el-form" :model="timeOptions" :label-position="'top'" :rules="timerFormRules">
          <el-form-item prop="timeTpye" v-if="timeOptions.timerTab === 'diy'">
            <template #label>
              <div class="title">{{ $t('connector.setting.label1') }}</div>
            </template>
            <el-radio-group v-model="timeOptions.executeType">
              <el-radio label="once">{{ $t('connector.setting.label4') }}</el-radio>
              <el-radio label="repeat">{{ $t('connector.setting.label5') }}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item prop="executeTs" v-if="timeOptions.executeType === triggerActionTypeEnum.Once && timeOptions.timerTab === 'diy'">
            <template #label>
              <div class="title">{{ $t('projectManage.setting.messageSetting.label4') }}</div>
            </template>
            <el-date-picker
              v-model="timeOptions.executeTs"
              type="datetime"
              value-format="timestamp"
              :placeholder="$t('common.placeholder.select')">
            </el-date-picker>
          </el-form-item>
          <el-form-item v-if="timeOptions.executeType === triggerActionTypeEnum.Repeat && timeOptions.timerTab === 'diy'">
            <template #label>
              <div class="title">{{ $t('connector.setting.label2') }}</div>
            </template>
            <div class="flex-x">
              {{ $t('common.base.per') }}
              <template v-if="timeUnit === 0">
                <!-- <el-input-number class=" mar-l-8 mar-r-8 w-100-box" v-model="timeOptions.secondNum" @change="handleChange" :min="1" :max="31" :controls="false"></el-input-number> -->
                <el-select class=" mar-l-8 mar-r-8 w-100-box" v-model="timeOptions.firstNum">
                  <el-option
                    v-for="(item, index) in 31"
                    :key="item"
                    :label="item"
                    :value="item">
                  </el-option>
                </el-select>
              </template>
              <template v-else-if="timeUnit === 1">
                <!-- <el-input-number class=" mar-l-8 mar-r-8 w-100-box" v-model="timeOptions.secondNum" @change="handleChange" :min="1" :max="72" :controls="false"></el-input-number> -->
                <el-select class=" mar-l-8 mar-r-8 w-100-box" v-model="timeOptions.secondNum">
                  <el-option
                    v-for="(item, index) in 72"
                    :key="item"
                    :label="item"
                    :value="item">
                  </el-option>
                </el-select>
              </template>
              <el-select class=" mar-l-8 mar-r-8 w-100-box" v-model="timeUnit" @change="timeUnitChange">
                <el-option
                  v-for="(item, index) in timeUnitOptions"
                  :key="item.key"
                  :label="item.label"
                  :value="item.key">
                </el-option>
              </el-select>
              <template v-if="timeUnit === 0">
                <el-select class=" mar-l-8 mar-r-8 w-100-box" v-model="timeOptions.secondNum">
                  <el-option
                    v-for="(item, index) in 24"
                    :key="index"
                    :label="index"
                    :disabled="timeOptions.firstNum === 0 && index === 0"
                    :value="index">
                  </el-option>
                </el-select>
                {{ $t('common.time.hour') }}
              </template>
            </div>
          </el-form-item>
          <el-form-item prop="finishTs" v-if="timeOptions.executeType === triggerActionTypeEnum.Repeat && timeOptions.timerTab === 'diy'">
            <template #label>
              <div class="title">{{ $t('common.time.processTime.endTime') }}</div>
            </template>
            <el-date-picker
              v-model="timeOptions.finishTs"
              type="datetime"
              value-format="timestamp"
              :placeholder="$t('common.placeholder.select')">
            </el-date-picker>
          </el-form-item>
          <el-form-item prop="expression" v-if="timeOptions.timerTab === triggerActionTypeEnum.Corn" >
            <template #label>
              <div class="title">CRON<span>({{ $t('connector.setting.tips2') }})</span></div>
            </template>
            <el-input v-model="timeOptions.expression" :placeholder="$t('common.placeholder.input2')"></el-input>
          </el-form-item>
          <el-form-item prop="param">
            <template #label>
              <div class="title">
                <span class="mar-r-8">{{ $t('connector.setting.label3') }}</span>
                <el-button type="text" @click="stringifyParams">{{ $t('connector.setting.btn1') }}</el-button>
                <el-button type="text" @click="openCodeHelp">编码规范及使用帮助</el-button>
              </div>
            </template>
            <el-input
            v-model="timeOptions.param"
            type="textarea"
            :placeholder="$t('common.placeholder.input2')"
            :autosize="{ minRows: 3, maxRows: 10 }"/>
          </el-form-item>
          
        
      </el-form>

    </div>
    <div class="action-app-form-item" v-if="currentExecuteWay === 'timeOutPlus'">
      <el-button style="width: 100%; margin-top: 10px" @click="changeShowOverTime">点击设置超时规则</el-button>
      <div class="timeOutPlus-content" v-if="!isRuleEmpty">
        <div class="timeOutPlus-item">
          <div class="timeOutPlus-item-title">超时类型：</div>
          <div class="timeOutPlus-item-content">超过某个时长</div>
        </div>
        <div class="timeOutPlus-item">
          <div class="timeOutPlus-item-title">规则：</div>
          <div class="timeOutPlus-item-content">当{{overTimeConfig.endTimeConfig}}减去{{overTimeConfig.startTimeConfig}}超过{{app.data.rule.durationConfig.value}}{{ app.data.rule.durationConfig.unit == 'h' ? '小时' : app.data.rule.durationConfig.unit == 'm' ? '分' : app.data.rule.durationConfig.unit == 'd' ? '天' : '' }}</div>
        </div>
      </div>
      <!-- <div class="timeOutPlus-content">
        <div class="timeOutPlus-item">
          <div class="timeOutPlus-item-title">超时类型：</div>
          <div class="timeOutPlus-item-content">超过某个时间点</div>
        </div>
        <div class="timeOutPlus-item">
          <div class="timeOutPlus-item-title">规则：</div>
          <div class="timeOutPlus-item-content">当{}减去{}超过小时</div>
        </div>
      </div> -->
      <overTimeDialog :show.sync="isShowOverTimeDialog" :fromApiId="fromApiId" @saveOverTimeDialog="saveOverTimeDialog" :appData="app.data"></overTimeDialog>
    </div>
  </div>
</template>
<script>
import * as triggerApi from '@src/modules/connector/api/trigger';
import { getTimeoutReminderField } from '@src/api/ConnectorApi'
import { isObject } from '@src/util/type'
import { t } from '@src/locales'
import { cloneDeep } from 'lodash';
import { triggerActionTypeEnum } from '@src/modules/connector/view/setting/components/workflow/components/drawers/type'
import { flowStore } from '@src/modules/connector/view/setting/components/workflow/store'
import { allowExecuteWay } from '@src/modules/connector/view/setting/common'
import overTimeDialog from './components/overTimeDialog.vue'

export default {
  name:'TriggerDrawer',
  props:{
    nodeConfig:{
      type:Object,
      default:()=>({})
    },
    parent:{
      type:Object,
      default:()=>({})
    },
  },
  computed:{
    timerOptionsByHttp(){
      return flowStore.timerOptions
    },
    canChoose(){
      return this.parent?.data?.bizTypeId
    },
    timerFormRules(){
      return {
        expression:{
          required: true,
          message: t('common.placeholder.input2'),
          trigger: 'blur',
        },
        param:{
          validator:(rule, value, callback) => {
            
            if (value !== '') {
              try {
                let res = JSON.parse(`${value}`)
                
                if(!isObject(res)){
                  callback(new Error(t('connector.setting.tips1')));
                }
              } catch (error) {
                console.error(error)
                callback(new Error(t('connector.setting.tips1')));
              }
            }
            callback();
          },
          trigger: 'blur',
        },
        executeTs:{
          validator:(rule, value, callback) => {
            
            if (value !== '') {
              if(value < new Date().getTime()){
                callback(new Error(t('common.base.tip.cannotBeEarlierThanNow', {data1:t('projectManage.setting.messageSetting.label4')})));
              }
            }
            callback();
          },
          trigger: 'blur',
        },
        finishTs:{
          validator:(rule, value, callback) => {
            if (value !== '') {
              if(value < new Date().getTime()){
                callback(new Error(t('common.base.tip.cannotBeEarlierThanNow', {data1:t('common.time.processTime.endTime')})));
              }
            }
            callback();
          },
          trigger: 'blur',
        },
      }
    },
    timeUnitOptions(){
      return [
        { label:t('common.time.day'), key:0},
        { label:t('common.time.hour'), key:1},
      ]
    },
    isRuleEmpty() {
      return Object.keys(this.app?.data?.rule || {}).length === 0;
    }
  },
  watch:{
    nodeConfig:{
      handler(newVal){
        this.app = newVal
        // console.log('trigger drawer app', this.app, this.parent)
      },
      deep:true,
      immediate:true
    },
    'parent.data.appId':{
      handler(newVal, oldVal){
        newVal && (newVal !== oldVal) && this.getActionList()
      },
      deep:true,
      immediate:true
    },
    currentExecuteWay:{
      handler(newVal){
        if(newVal) {
          console.log(newVal, 'newValnewVal')
          let { options, wayName } = this.executeWayList.filter(item=>item.way === newVal)[0]
          if(newVal === 'webhook') {
            // webhook 特殊处理
            this.webHookConfig = options
            try {
              if(isObject(this.webHookConfig.paramTemplate)) {
                this.webHookConfig.paramTemplate = JSON.stringify(this.webHookConfig.paramTemplate, null, 2);
              }
            } catch (error) {
              console.warn(error)
            }
          } else if (newVal === 'timer'){
            this.timeOptions = {...this.timeOptions, ...(this.timeOptionsStash ? this.timeOptionsStash : (this.timerOptionsByHttp || {}))}
            if(isObject(this.timeOptions.param)){
              this.timeOptions.param = JSON.stringify(this.timeOptions.param)
            }
            if(this.timeOptions.executeType === triggerActionTypeEnum.Corn){
              this.timeOptions.timerTab = triggerActionTypeEnum.Corn
            }else{
              this.timeOptions.timerTab = 'diy'
              if(this.timeOptions.firstNum === 0){
                this.timeUnit = 1
              }else{
                this.timeUnit = 0
              }
            }
            if(!this.timeOptionsStash){
              this.timeOptionsStash = cloneDeep(this.timeOptions)
            }
            
          } else if (newVal == 'timeOutPlus') {
            this.loading = true;
            getTimeoutReminderField({
              fromApiId: this.fromApiId,
            }).then(res => {
              this.overTimeFromConfig = res.data || {}
              let endTimeConfig, startTimeConfig;
              this.overTimeFromConfig.forEach(item => {
                if (item.enName === this.app.data.rule?.endTimeConfig?.value) {
                  endTimeConfig = item.cnName;
                } else if (item.enName === this.app.data.rule?.startTimeConfig?.value) {
                  startTimeConfig = item.cnName;
                }
              })
              this.overTimeConfig = {
                endTimeConfig,
                startTimeConfig,
              }
              this.options = options
              this.loading = false;
            })
          } else {
            this.options = options
          }
          const data = {
            ...this.app.data,
            bizActionCode: newVal,
            bizActionName: wayName,
            paasNodeId: this.parent?.data?.bizActionCode || '',
            url: this.webHookConfig.url,
            paramTemplate: this.webHookConfig.paramTemplate,
          }

          this.app.data = data
          this.stashData = data
          this.$emit('update:nodeConfig', this.app)
        }
      },
      deep:true,
      immediate:true
    },
    'timeOptions.timerTab'(newVal){
      this.$refs.actionByTimeFormDom.clearValidate()
      if(newVal === 'diy' && this.timeOptions.executeType === triggerActionTypeEnum.Corn){
        this.timeOptions.executeType =  triggerActionTypeEnum.Once
      }
    }
  },
  data(){
    return{
      triggerActionTypeEnum,
      loading: false,
      app:this.nodeConfig,
      executeWayList: [],
      currentExecuteWay: '',
      webHookConfig: {
      },

      action: [],
      options:[],
      timeOptions:{
        executeType: triggerActionTypeEnum.Once,
        secondNum:0,
        firstNum:1,
        timerTab:'diy',
        executeTs:'',
        param:'',
        finishTs:'',
      },
      timeOptionsStash: null,
      props:{
        emitPath:false,
        value:'bizActionCode',
        label:'bizActionName',
        children:'children',
        multiple: true,
      },
      stashData:null,
      timeUnit:0,
      isShowOverTimeDialog: false,
      fromApiId: this.parent?.data?.bizTypeId,
      overTimeFromConfig: {},
      overTimeConfig: {
        endTimeConfig: '',
        startTimeConfig: '',
      },
    }
  },
  methods:{
    copyLink(data) {
      if(isObject(data)) {
        data = JSON.stringify(data, null, 2);
      }
      let input = document.createElement('input')
      input.value = data
      input.setAttribute('style', 'position:fixed;top:-100%')
      document.body.appendChild(input)
      input.select()
      document.execCommand('copy')
      input.remove()
      this.$message.success(this.$t('common.base.tip.copySuccess'));
    },
    handleTreeSelect(val){
      let node = this.$refs.TriggleActionSelectComponent.getCheckedNodes(true) || []
      // console.log('draw trigger handleTreeSelect', val, node)
      let data = {
        bizActionName:'',
        bizActionCode:'',
        paasNodeId:''
      }
      
      if(node.length) {
        let eventOptionList = []

        node.forEach(x => {
          if(x.data?.bizActionCode){
            let {bizActionName, bizActionCode} = x.data
            data = {bizActionName, bizActionCode}
            let { pathLabels } = x
            // 如果有多级的时候显示全部路径
            if(pathLabels && pathLabels.length) {
              data.bizActionName = pathLabels.join('/')
            }
            data.paasNodeId = x.parent?.data?.bizActionCode || ''

            eventOptionList.push({
              bizActionName,
              bizActionCode,
              paasNodeId: x.parent?.data?.bizActionCode || ''
            })
          }
        })
        data.eventOptionList = eventOptionList;
      }
      // this.app.childNodes = []
      this.app.data = { ...this.app.data, ...data }
      this.$emit('update:nodeConfig', this.app)
    },
    getQueryString(name) {
      let reg = new RegExp(`(^|&)${name}=([^&]*)(&|$)`, 'i');
      let search = window.location.search;
      let r = search.substr(1).match(reg);
      if (r != null) {
        return decodeURIComponent(r[2]);
      }
      return null;
    },
    getActionList(){
      let fromApiId = this.parent?.data?.bizTypeId
      if(!fromApiId) return;
      const triggerId = this.getQueryString('id') || ''
      const params = { fromApiId }
      if(triggerId) params.triggerId = triggerId
      this.loading = true
      triggerApi.getExecuteConfig(params).then(res=>{
        this.loading = false
        if(res.status == 0){
          this.executeWayList = (res.data || []).map(item=> {
            if(item.way === 'event') {
              item.options = (item.options.actionList || []).map(action=> {
                if(action.children?.length) {
                  action.children.forEach(node=>{
                    node.bizActionCode = `${action.bizActionCode}/${node.bizActionCode}`
                  })
                } else {
                  action.children = null
                }
                return action
              })
            }else if(item.way === 'timer'){
              flowStore.setParam(item.options?.param || {})
            }
            return item  
          })
          const { bizActionCode, currentExecuteWay, eventOptionList } = this.app.data
          if(bizActionCode){
            this.currentExecuteWay = allowExecuteWay.includes(bizActionCode) ? bizActionCode : 'event'
          } else {
            this.currentExecuteWay = this.executeWayList[0]?.way || ''
          }
          if(currentExecuteWay){
            this.currentExecuteWay = currentExecuteWay
          }
          if(this.currentExecuteWay === 'event') {
            this.action = (eventOptionList || []).map(x => x.action || x.bizActionCode);
            const { options } = (this.executeWayList || []).filter(item=>item.way === 'event')[0]
            this.options = options
          }
          
          // this.options = (options.actionList || []).map(item=>{
          //   (item.children || []).forEach(node=>{
          //     node.bizActionCode = `${item.bizActionCode}/${node.bizActionCode}`
          //   })
          //   return item
          // })
          // if(this.options.findIndex(item=>{return item.bizActionCode == this.app.data.bizActionCode}) == -1 && this.options.findIndex(item=>{return item.bizActionCode == this.app.data.paasNodeId}) == -1){
          //   this.app.data = {
          //     bizActionName:'',
          //     bizActionCode:'',
          //     paasNodeId:''
          //   }
          //   this.$emit('update:nodeConfig', this.app)
          // }
        }
      }).finally(()=> this.loading = false)
    },
    stringifyParams(){
      try {
        let json = JSON.parse(this.timeOptions.param);
        this.timeOptions.param = JSON.stringify(json, null, '\t')
      } catch (error) {
        console.error(error)
      }
      
    },
    async getTimerOptions(){
      if(this.currentExecuteWay !== 'timer') return null
      let formValidator = await this.$refs.actionByTimeFormDom.validate()
      if(!formValidator) return false
      this.timeOptionsStash = cloneDeep({...this.timeOptions})
      
      const { param, executeTs, timerTab, executeType, secondNum, firstNum, expression, finishTs } = this.timeOptions
      const { bizActionName, bizActionCode } = this.app.data
      let param_ = param ? JSON.parse(param) : param
      let timeOptions_ = { param:param_ }
      if(timerTab === triggerActionTypeEnum.Corn){
        timeOptions_['executeType'] = triggerActionTypeEnum.Corn
        timeOptions_['expression'] = expression
      }else {
        if (executeType === triggerActionTypeEnum.Once){
          timeOptions_['executeType'] = executeType
          timeOptions_['executeTs'] = executeTs
        }else if(executeType === triggerActionTypeEnum.Repeat){
          timeOptions_['executeType'] = executeType
          timeOptions_['firstNum'] = firstNum
          timeOptions_['secondNum'] = secondNum
          timeOptions_['finishTs'] = finishTs
        }
      }
      let res = cloneDeep({...timeOptions_, bizActionName, bizActionCode})
      flowStore.setTimerOptions(res)
      return res
    },
    timeUnitChange(e){
      if(e === 0 ){
        this.timeOptions.firstNum = 1
        this.timeOptions.secondNum = 0
      }else{
        this.timeOptions.firstNum = 0
        this.timeOptions.secondNum = 1
      }
    },
    changeShowOverTime(){
      this.isShowOverTimeDialog = !this.isShowOverTimeDialog;
    },
    saveOverTimeDialog(data){
      let clonedata = JSON.parse(JSON.stringify(data));
      this.app.data = { ...this.app.data, ...clonedata };
      let endTimeConfig, startTimeConfig;
      this.overTimeFromConfig.forEach(item=>{
        if(item.enName === this.app.data.rule?.endTimeConfig?.value){
          endTimeConfig = item.cnName;
        }else if(item.enName === this.app.data.rule?.startTimeConfig?.value){
          startTimeConfig = item.cnName;
        }
      })
      this.overTimeConfig = {
        endTimeConfig,
        startTimeConfig,
      }
      this.$emit('update:nodeConfig', this.app);
    },
    // 打开编码规范及使用帮助
    openCodeHelp(){
      window.open('https://doc.shb.ltd/shb_xoqazk/ia4qctp2ly559d1m/gre7yumc5sz4ewod/dklg7gkm64cya8l4/ox8c8k8i3hp1g6do.html');
    },
  },
  components:{
    overTimeDialog,
  }
}
</script>
<style lang="scss">
.action-app-form-item {
  .trigger-tip {
    font-size: 12px;
  }
  .url-input {
    display: flex;
    .el-button {
      margin-left: 12px;
    }
  }
  .el-form-item {
    .el-form-item__content {
      margin-left: 0!important;
      .del {
        cursor: pointer;
      }
    }
  }
  .el-form-item--small.el-form-item{
    margin-bottom: 8px;
  }
  .webhook-config-param-template {
    display: flex;
    justify-content: center;
    .el-textarea__inner {
      background-color: #F5F5F5!important;
      color: #C0C4CC!important;
    }
    .el-button {
      height: 32px;
      margin-left: 12px;
    }
  }

  .max-w-50-p{
    max-width: 50%;
  }
  .w-100-p{
    width: 100%;
  }
  .el-form-item.is-required:not(.is-no-asterisk) > .el-form-item__label:before, .el-form-item.is-required:not(.is-no-asterisk) .el-form-item__label-wrap > .el-form-item__label:before{
    margin-top: 12px;
  }
}
.trigger-action-select {
  border-radius: 4px!important;
  background-color: #fff !important;
  width: 100%;
  .el-input.is-disabled .el-input__inner {
    background-color: #fff !important;
  }
}
.timeOutPlus-content {
  background-color: #f0f0f0;
  margin-top: 10px;
  border-radius: 4px;
  overflow: hidden;
  padding: 15px 10px 5px;
  .timeOutPlus-item {
    display: flex;
    justify-content: center;
    align-items: center;
    margin-bottom: 10px;
    &-title {
      width: 80px;
    }
    &-content {
      flex: 1;
    }
  }
}
</style>
